<template>
    <aside class="left-div">
        <header class="header">
            <h2>控制面板</h2>
        </header>
        <section class="info-panel">
            <h3>温度控制</h3>
            <button @click="toggleTemperatureModels">切换温度模型</button>
            <div></div>
            <label>温度值渲染范围:10-21</label>            
            <h3>水深控制</h3>
            <button @click="togglewaterDepthModels">切换水深模型</button>
            <div></div>
            <label>水深值渲染范围:0-4</label>
            <h3>Z值变化显示</h3>
            <button @click="toggleZValueModels">切换Z值显示模型</button>
            <div></div>
            <label>Z值渲染范围:10-25</label>
            <div>
                <h3>模型控制</h3>
                <button @click="removeModels">移除模型</button>
                <div></div>
            </div>
 
      </section>
      
    </aside>

    <!-- ------------未完成内容，计算新增日期文件名称显示及色带展示------------- -->
    <div class="container">
        <!-- 文件名称显示 -->
        <label class="file-name">{{ fileName }}</label>

        <!-- 色带条 -->
        <div class="ribbon-container">
            <div class="ribbon" :style="{ backgroundColor: ribbonColor }"></div>
            <span class="ribbon-value">{{ ribbonValue }}</span>
        </div>
    </div>
</template>

<script setup lang='ts'>
import * as Cesium from 'cesium';
import { defineProps, toRefs, onMounted, watch ,ref } from 'vue';

import { proj4548ToProj4326 } from '../../scripts/corrdinateProj.ts';
import { LoadGLBFromURL } from '../../scripts/loadglb.ts';
import {GetFileURL} from '../../scripts/ToolFunctions/getImgFromUrl.ts';

// 文件名、色带颜色和数值的响应式引用
const fileName = ref('未命名文件');
const ribbonColor = ref('#0000ff');
const ribbonValue = ref(0);
// 更新文件名的方法
function updateFileName(newName) {
  fileName.value = newName;
}

// 更新色带颜色和数值的方法
function updateRibbon(color, value) {
  ribbonColor.value = color;
  ribbonValue.value = value;
}
//------------未完成内容，计算新增日期文件名称显示及色带展示------------------

// 定义接收的 props
const props = defineProps<{
    viewer: Cesium.Viewer | null;
}>();

// 使用 toRefs 解构 props 保持响应式
const { viewer } = toRefs(props);


// NOTE:通过使用 watch 函数，确保在 viewer 可用时再进行操作
let isViewerInitialized = false;
// 添加watch函数，确保viewer对象已被赋值
watch(viewer, (newViewer) => {
    if (newViewer && !isViewerInitialized) {
        // 设置相机视角
        newViewer.camera.setView({
            destination: Cesium.Cartesian3.fromDegrees(113.3436, 29.8385, 50000),
            orientation: {
            heading: Cesium.Math.toRadians(345),
            pitch: Cesium.Math.toRadians(-90),
            roll: 0
        }
        });
        isViewerInitialized = true;
    }
});

// 使用 onMounted 生命周期钩子，无法访问到已被赋值的viewer
onMounted(() => {
    // 在这里可以使用 viewer 来访问 Cesium 的 viewer 实例。但直接访问时，变量还未初始化
    // console.log(viewer.scene);//undefined
});



const originX = 432940.90625;
const originY = 3288375.0;
const lonlatPos = proj4548ToProj4326(originX,originY);
// console.log(`orogin point lonlatPos is lon:${lonlatPos[0]}, lat:${lonlatPos[1]}`);




//全局对象，存储当前加载显示的洪湖模型
let mesh:Cesium.Model = null;

let currentIndex = 0; // 当前显示的索引
let currentUrl = ""; // 当前显示的 URL

let switchInterval: number | undefined; // 定时器 ID

let fileUrls: string[] = []; // 确保fileUrls是一个数组类型


// TODO:
// 1.新增色带与值范围的“图例”
// 2.新增当前文件名称展示

async function toggleTemperatureModels(){
    // console.log("viewer is ",viewer.value);
    // console.log(" scene is ",viewer.value.scene);
    // TODO:

    // // INFO:加载单个模型
    // const glbUrl = 'http://127.0.0.1:8082/temperture_10_21_5_level/HYD_2023_12_2_1_0_0.glb';
    // let lakeMesh = await LoadGLBFromURL(glbUrl,viewer.value,lonlatPos[0],lonlatPos[1]);
    // console.log("lakeMesh:",lakeMesh);

    // INFO:加载多个模型并进行切换
    // 替换为自己的模型文件地址
    const temperatureUrl = "http://127.0.0.1:8082/temperture_10_21_5_level/";
    // 初始化图片加载
    await initializeIChanges(temperatureUrl);

}

async function togglewaterDepthModels(){
    // INFO:加载多个模型并进行切换
    // 替换为自己的模型文件地址
    const waterDepthUrl = "http://127.0.0.1:8082/waterDepth_0_4_5_level/";
    // 初始化图片加载
    await initializeIChanges(waterDepthUrl);
}

async function toggleZValueModels(){
    // 替换为自己的模型文件地址
    const zValueUrl = "http://127.0.0.1:8082/WQR_Z_10_25/";
    // 初始化图片加载
    await initializeIChanges(zValueUrl);
}


async function SwitchModelFromURL(url:string,viewer:Cesium.Viewer){
    if(mesh){
        viewer.scene.primitives.remove(mesh);
    
        // viewer.scene.primitives.removeAll();
    }

    
    // console.log("切换加载的模型");
    mesh = await LoadGLBFromURL(url,viewer,lonlatPos[0],lonlatPos[1]);
}

async function initializeIChanges(baseUrl:string) {
    try {
        fileUrls = await GetFileURL(baseUrl,'.glb');
        // console.log("fileUrls:", fileUrls);

        if (fileUrls.length > 0) {
            // 初始化第一个文件
            currentUrl = fileUrls[currentIndex];
            // console.log("Switching to first image URL:", currentUrl);

            // 开始轮换
            startSwitching();
        } else {
            console.error("No images available for switching.");
        }
    } catch (error) {
        console.error("Error fetching images:", error);
    }
}

// 开始轮换
function startSwitching() {
    switchInterval = setInterval(SwitchModels, 1000); // 每 1 秒切换一次，可根据需求调整时间间隔
}

// 停止轮换
function stopSwitchingModels() {
    if (switchInterval !== undefined) {
        clearInterval(switchInterval);
        console.log('轮换已停止');
    }
}

// 切换
function SwitchModels() {
    currentIndex = (currentIndex + 1) % fileUrls.length;
    const newUrl = fileUrls[currentIndex];

    if(currentIndex == fileUrls.length - 1){
        stopSwitchingModels();
        // currentIndex = 0;

    }else{
        // 如果新旧URL不同，则更新
        if (newUrl !== currentUrl) {
            currentUrl = newUrl;
            console.log("Switching to new URL:", currentUrl);

            SwitchModelFromURL(currentUrl, viewer.value);
        }
    }
 
}

// 必须等模型加载完毕之后才可移除
function removeModels(){
    if(mesh){
        viewer.value.scene.primitives.remove(mesh);
    
        // viewer.scene.primitives.removeAll();
    }else{
        console.error("mesh is null");
    }
}

</script>

<style scoped>
.left-div {
width: 200px;
height: 80%;
background-color: #f8f9fa;
position: fixed;
top: 0;
left: 0;
padding: 15px;
box-sizing: border-box;
transition: opacity 0.3s ease-in-out; /* 平滑过渡效果 */
}

.header,
.info-panel {
margin-bottom: 20px;
}

/* -----------------未完成内容，新增色带效果-------------- */
.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* 使用space-between让顶部和底部元素尽可能远离 */
  align-items: center;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none; /* 确保此元素下的Cesium容器可以接收鼠标事件 */
}

.file-name, .ribbon-container {
  pointer-events: auto; /* 使这些元素可交互 */
}

.file-name {
  font-size: 24px;
  margin-top: 20px;
}

.ribbon-container {
  text-align: center;
  width: 50%;
  margin-bottom: 10%; /* 设置底部间距为20% */
}

.ribbon {
  height: 20px;
  width: 80%;
  margin: 0 auto;
}

.ribbon-value {
  display: block;
  text-align: center;
  margin-top: 5px;
}
</style>
